﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WoSoft.PACS.Data.Models;
using WoSoft.PACS.Data.CheckData;
using DevComponents.DotNetBar;
using WoSoft.PACS.Data.CheckItem;
using WoSoft.PACS.Data.DataSourceData;
using WoSoft.PACS.Data.ModelsExt;
using WoSoft.PACS.Win.Properties;

namespace WoSoft.PACS.Win.Forms.SubForms
{
    /// <summary>
    /// 检查申请
    /// </summary>
    public partial class FrmCheckApp : FrmBase
    {
        bool EasyMode = false;//是否简易模式
        CheckApp checkApp = new CheckApp();

        public FrmCheckApp()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 创建的申请ID,用于病人定位与加载申请数据
        /// </summary>
        public string AppCheckID { get; set; }

        /// <summary>
        /// 检查类型
        /// </summary>
        public string AppCheckType { get; set; }

        //选择病人
        private void tbPatientName_ButtonCustomClick(object sender, EventArgs e)
        {
            var text = this.tbPatientName.Text.Trim();
            FrmPatientSearch patientSearch = new FrmPatientSearch(text);
            patientSearch.ShowDialog(this);
            if (patientSearch.PatientInfo != null)
            {
                this.tbPatientName.Text = patientSearch.PatientInfo.姓名;
                this.tbPatientName.Tag = patientSearch.PatientInfo.ID;
                this.tbCode.Text = patientSearch.PatientInfo.简码;
                this.tbAge.Text = patientSearch.PatientInfo.出生日期 != DateTime.MaxValue ? (DateTime.Now.Year - patientSearch.PatientInfo.出生日期.Year).ToString() : string.Empty;
                this.dtBirthday.Value = patientSearch.PatientInfo.出生日期;
            }
        }

        CheckItemDataService checkItemDataService = new CheckItemDataService();
        //加载默认值
        private void FrmCheckApp_Load(object sender, EventArgs e)
        {
            EasyMode = Settings.Default.EasyMode;
            
            //加载性别
            this.LoadSexList(this.cbSext);

            //加载科室
            this.LoadDepartment(this.cbAppDepartment);

            //加载操作员
            this.LoadUser(this.cbExeUser);
            this.cbExeUser.Text = Program.yhmc;

            //加载执行科室
            this.LoadDepartment(this.cbExeDepartment);
            this.cbExeDepartment.SelectedValue = Program.CurrentLoginUser.DepartmentID;

            this.SetSpellCodeControl(this.tbPatientName, this.tbCode);

            this.cbExeDepartment.SelectedValueChanged += new EventHandler(cbExeDepartment_SelectedValueChanged);
            if (this.cbExeDepartment.SelectedValue != null)
            {
                this.LoadDoctorToCombox(this.cbExeDepartment.SelectedValue.ToString(), this.cbExeDoctor);
                this.cbExeDoctor.SelectedValue = Program.CurrentLoginUser.DoctorID;
            }

            //加载科室下的医生
            if (this.cbAppDepartment.SelectedValue != null)
            {
                this.LoadDoctorToCombox(this.cbAppDepartment.SelectedValue.ToString(), this.cbAppDoctor);
            }

            //加载检查类别
            this.cbCheckType.SelectedIndexChanged -= new EventHandler(cbCheckType_SelectedIndexChanged);
            var dt = checkItemDataService.GetCheckItemFlAllData();
            cbCheckType.DataSource = dt;
            cbCheckType.DisplayMember = "名称";
            cbCheckType.ValueMember = "ID";
            cbCheckType.SelectedIndex = -1;
            this.cbCheckType.SelectedIndexChanged += new EventHandler(cbCheckType_SelectedIndexChanged);

            if (string.IsNullOrEmpty(AppCheckID))
            {//直接申请模式
                //默认是岁
                this.cbAgeUnit.SelectedIndex = 0;
                this.dtBirthday.Value = DateTime.Now;
                this.dtAppTime.Value = DateTime.Now;
                this.tbPatientName.Tag = "";
                this.cbCheckType.SelectedValue = WoSoft.PACS.Win.Properties.Settings.Default.DefaultCheckType;
                this.rbMz.Checked = true;
                if (EasyMode) this.ActiveControl = this.tbPatientName;
            }
            else
            {
                //加载,进行报到的数据
                LoadDataByAppFormID();

                //设置报到控件可用性
                SetControl();

                this.ActiveControl = this.btnOK;
            }
        }
        //检查项目
        void cbCheckType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var dt = checkItemDataService.GetCheckByCID(cbCheckType.SelectedValue.ToString());
            cbItems.DataSource = dt;
            cbItems.DisplayMember = "项目名称";
            cbItems.ValueMember = "ID";
            cbItems.Text = "";
            cbItems.SelectedIndex = -1;
        }
         

        //根据申请ID加载申请记录数据
        private void LoadDataByAppFormID()
        {
            var dr = checkApp.GetCheckAppByID(this.AppCheckID);
            if (dr != null)
            {
                this.cbPatientType.Text = dr["申请来源"].ToString();
                switch (dr["申请来源"].ToString())
                {
                    case "门诊":
                        rbMz.Checked = true;
                        break;
                    case "住院":
                        rbZy.Checked = true;
                        break;
                    case "体检":
                        rbTj.Checked = true;
                        break;
                    default:
                        break;
                }
                this.tbPatientID.Text = dr["申请条码"].ToString();
                this.tbPatientName.Tag = dr["个人ID"].ToString();
                this.tbPatientName.Text = dr["姓名"].ToString();
                this.tbCode.Text = dr["简码"] != null ? dr["简码"].ToString() : string.Empty;
                this.cbSext.SelectedValue = dr["性别"] != null ? dr["性别"].ToString() : "0";
                this.tbAge.Value = dr["年龄"] != null ? Convert.ToInt32(dr["年龄"]) : 0;
                this.cbAgeUnit.SelectedIndex = dr["年龄单位"] != null ? Convert.ToInt32(dr["年龄单位"]) : 0;
                this.tbHeight.Value = dr["身高"] != null ? Convert.ToDouble(dr["身高"]) : 0.0;
                this.tbWeight.Value = dr["体重"] != null ? Convert.ToDouble(dr["体重"]) : 0.0;
                this.tbBednum.Text = dr["床号"].ToString();
                if (dr["出生日期"] != null)
                {
                    this.dtBirthday.Value = Convert.ToDateTime(dr["出生日期"]);
                }

                this.cbCheckType.Text = dr["检查类型"] != null ? dr["检查类型"].ToString() : string.Empty;
                this.tbInterfaceCode.Text = dr["接口项目代码"] != null ? dr["接口项目代码"].ToString() : string.Empty;
                this.cbItems.Text = dr["检查项目名称"] != null ? dr["检查项目名称"].ToString() : string.Empty;
                this.tbDiagnose.Text = dr["临床诊断"] != null ? dr["临床诊断"].ToString() : string.Empty;
                //this.tbCheckPositionMothod.Text = dr["检查部位方法"] != null ? dr["检查部位方法"].ToString() : string.Empty;
                this.tbAppTaget.Text = dr["检查目的"] != null ? dr["检查目的"].ToString() : string.Empty;
                this.tbRemark.Text = dr["注意事项"] != null ? dr["注意事项"].ToString() : string.Empty;

                this.cbAppDepartment.SelectedValue = dr["申请科室ID"] != null ? dr["申请科室ID"] : string.Empty;
                var docText = dr["申请医生"] != null ? dr["申请医生"].ToString() : string.Empty;
                if (this.cbAppDoctor.Items != null)
                {
                    foreach (var item in this.cbAppDoctor.Items)
                    {
                        DataRowView cbitem = item as DataRowView;
                        if (cbitem["姓名"].ToString() == docText)
                        {
                            this.cbAppDoctor.SelectedItem = cbitem;
                            break;
                        }
                    }
                }

                if (dr["申请时间"]!=null)
                {
                    this.dtAppTime.Value = Convert.ToDateTime(dr["申请时间"]);
                }

                var dj = dr["单据性质"] != null ? Convert.ToInt32(dr["单据性质"]) : 0;
                if (dj==0)
                {
                    this.ckFree.Checked = true;
                }
                else if(dj ==1)
                {
                    this.ckClacFee.Checked = true;
                }
                else
                {
                    this.ckRecordFee.Checked = true;
                }

                //是否急诊
                var isjz = dr["是否急诊"] != null ? Convert.ToBoolean(dr["是否急诊"]) : false;
                this.ckEmergency.Checked = isjz;
                this.cbExeUser.Text = dr["录入人员"].ToString();
            }
        }

        //设置控件属性
        private void SetControl()
        {
            this.rbMz.Enabled = false;
            this.rbZy.Enabled = false;
            this.rbTj.Enabled = false;
            this.cbPatientType.Enabled = false;
            this.tbPatientID.Enabled = false;
            this.tbPatientName.Enabled = false;
            this.tbCode.Enabled = false;
            this.cbSext.Enabled = false;
            this.tbAge.Enabled = false;
            this.cbAgeUnit.Enabled = false;
            this.tbHeight.Enabled = false;
            this.tbWeight.Enabled = false;
            this.tbBednum.Enabled = false;
            this.dtBirthday.Enabled = false;
            this.cbItems.Enabled = false;
            this.tbDiagnose.Enabled = false;
            this.tbAppTaget.Enabled = false;
            this.tbRemark.Enabled = false;
            this.cbCheckType.Enabled = false;
            this.cbAppDepartment.Enabled = false;
            this.cbAppDoctor.Enabled = false;
            this.dtAppTime.Enabled = false;
            this.ckClacFee.Enabled = false;
            this.ckFree.Enabled = false;
            this.ckEmergency.Enabled = false;
            this.ckRecordFee.Enabled = false;
            //this.tbCheckPositionMothod.Enabled = false;
            this.ckOK.Visible = false;
        }

        void cbExeDepartment_SelectedValueChanged(object sender, EventArgs e)
        {
            if (this.cbExeDepartment.SelectedValue != null)
            {
                this.LoadDoctorToCombox(this.cbExeDepartment.SelectedValue.ToString(), this.cbExeDoctor);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //保存数据
        private void btnOK_Click(object sender, EventArgs e)
        {
            AppCheckType = this.cbCheckType.Text.Trim();//检查类别

            if (string.IsNullOrEmpty(this.AppCheckID))//直接申请
            {
                var appid = SaveData();
                if (!string.IsNullOrEmpty(appid))
                {
                    AppCheckID = appid;
                }
                else
                {
                    return;
                }
            }
            else//报到确认
            {
                this.errorProvider1.Clear();
                if (this.cbExeDepartment.SelectedValue==null)
                {
                    this.errorProvider1.SetError(this.cbExeDepartment, "请选择一个执行科室");
                    return;
                }

                if (this.cbExeDoctor.SelectedValue == null)
                {
                    this.errorProvider1.SetError(this.cbExeDoctor, "请选择一个执行医生");
                    return;
                }
                //执行报到
                checkApp.CheckAppBaodao(this.AppCheckID, this.cbExeDepartment.SelectedValue.ToString(), this.cbExeDoctor.Text,Program.CurrentLoginUser.Name);
            }
            this.DialogResult = DialogResult.OK;
        }

        private string SaveData()
        {
            this.errorProvider1.Clear();

            if (EasyMode)
            {
                if (tbPatientName.Text.Trim() == string.Empty)
                {
                    this.errorProvider1.SetError(this.tbPatientName, "请输入病人姓名");
                    return "";
                }
            }
            else
            {
                if (object.Equals(((DevComponents.Editors.ComboItem)this.cbPatientType.SelectedItem), null))
                {
                    this.errorProvider1.SetError(this.cbPatientType, "请选择病人类型");
                    return "";
                }

                if (tbPatientName.Text.Trim() == string.Empty)
                {
                    this.errorProvider1.SetError(this.tbPatientName, "请输入病人姓名");
                    return "";
                }

                if (this.tbAge.Value == 0 || this.dtBirthday.Value == DateTime.MinValue)
                {
                    this.errorProvider1.SetError(this.tbAge, "请填写年龄");
                    return "";
                }

                if (this.cbAgeUnit.SelectedItem == null)
                {
                    this.errorProvider1.SetError(this.cbAgeUnit, "请选择年龄单位");
                    return "";
                }

                if (this.cbCheckType.Text.Trim() == string.Empty)
                {
                    this.errorProvider1.SetError(this.cbCheckType, "请录入或选择检查类型");
                    return "";
                }

                if (this.cbItems.Text.Trim() == string.Empty)
                {
                    this.errorProvider1.SetError(this.cbItems, "请录入或选择检查项目");
                    return "";
                }

                if (this.cbAppDepartment.SelectedValue == null)
                {
                    this.errorProvider1.SetError(this.cbAppDepartment, "请选择一个申请科室");
                    return "";
                }

                if (this.cbAppDoctor.SelectedValue == null)
                {
                    this.errorProvider1.SetError(this.cbAppDoctor, "请选择一个申请医生");
                    return "";
                }

                if (this.cbExeDepartment.SelectedValue == null && this.ckOK.Checked)
                {
                    this.errorProvider1.SetError(this.cbExeDepartment, "请选择一个检查科室");
                    return "";
                }

                if (this.cbExeDoctor.SelectedValue == null && this.ckOK.Checked)
                {
                    this.errorProvider1.SetError(this.cbExeDoctor, "请选择一个检查医生");
                    return "";
                }
            }

            var model = new CheckAppModel()
            {
                //id = Guid.NewGuid().ToString(),
                AppSource = ((DevComponents.Editors.ComboItem)this.cbPatientType.SelectedItem).Value.ToString(),
                ApplyCode = this.tbPatientID.Text.Trim(),
                Name = this.tbPatientName.Text.Trim(),
                //PatentID = this.tbPatientName.Tag.ToString() != "" ? this.tbPatientName.Tag.ToString() : Guid.NewGuid().ToString().ToUpper(),
                PatentID = this.tbPatientName.Tag.ToString(),
                Code = this.tbCode.Text.Trim(),
                Sex = Convert.ToInt32(this.cbSext.SelectedValue),
                Age = this.tbAge.Value,
                AgeUnit = ((DevComponents.Editors.ComboItem)this.cbAgeUnit.SelectedItem).Value.ToString(),
                Height = Convert.ToDecimal(this.tbHeight.Value),
                Weight = Convert.ToDecimal(this.tbWeight.Value),
                BedNum=tbBednum.Text.Trim(),

                Birthday = this.dtBirthday.Value,
                InterFaceCode=this.tbInterfaceCode.Text.Trim(),
                CheckItemName = this.cbItems.Text.Trim(),
                //CheckPositionMothod=this.tbCheckPositionMothod.Text.Trim(),
                Diagnosis = this.tbDiagnose.Text.Trim(),
                CheckAppTaget = this.tbAppTaget.Text.Trim(),
                Remark = this.tbRemark.Text.Trim(),
                AppNo = this.tbAppNo.Text.Trim(),

                OrgderProperties = this.ckFree.Checked ? 0 : this.ckClacFee.Checked ? 1 : 2,
                IsEmergency = this.ckEmergency.Checked,
                CheckType = this.cbCheckType.Text.Trim(),
                CheckAppTime = this.dtAppTime.Value,
                State = this.ckOK.Checked ? 2 : 1,
                CheckAppDoctor = this.cbAppDoctor.Text.Trim(),
                CheckAppDepartment = this.cbAppDepartment.SelectedValue != null ? this.cbAppDepartment.Text : string.Empty,
                CheckAppDepartmentID=this.cbAppDepartment.SelectedValue != null ? this.cbAppDepartment.SelectedValue.ToString() : string.Empty,
                Operation = Program.CurrentLoginUser.Name,
                OperationUser=this.cbExeUser.Text.Trim()
            };

            if (this.ckOK.Checked)
            {
                model.ExecuteDepartmentID = this.cbExeDepartment.SelectedValue != null ? this.cbExeDepartment.SelectedValue.ToString() : string.Empty;
                model.CheckDoctor = this.cbExeDoctor.SelectedValue != null ? this.cbExeDoctor.Text.ToString() : string.Empty;
                model.IsBD = true;
            }

            var appid = checkApp.CreateCheckApp(model);
            if (appid != string.Empty)
            {
                //MessageBoxEx.Show("创建申请记录成功", "申请", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBoxEx.Show("创建申请记录失败", "申请", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            return appid;
        }

        //年龄离开焦点时发生
        private void tbAge_Validating(object sender, CancelEventArgs e)
        {
            this.dtBirthday.Value = DateTime.Now.AddYears(0 - this.tbAge.Value);
        }

        //科室改变时加载医生
        private void cbDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbAppDepartment.SelectedValue != null)
            {
                this.LoadDoctorToCombox(this.cbAppDepartment.SelectedValue.ToString(), this.cbAppDoctor);
            }
        }

        //直接报到事件
        private void ckOK_CheckedChanged(object sender, EventArgs e)
        {
            this.lblDepartment.Visible = this.ckOK.Checked;
            this.lblDoctor.Visible = this.ckOK.Checked;
            this.cbExeDepartment.Visible = this.ckOK.Checked;
            this.cbExeDoctor.Visible = this.ckOK.Checked;

        }

        //病人信息录入回车事件
        private void tbPatientName_KeyDown(object sender, KeyEventArgs e)
        {
            //判断回车 
            if (e.KeyCode == Keys.Enter)
            {
                //tbPatientName_ButtonCustomClick(null, null);
            }
        }

        private void tbPatientID_KeyDown(object sender, KeyEventArgs e)
        {
            //判断回车 
           if (e.KeyCode == Keys.Enter)
            {
                tbPatientID_ButtonCustomClick(sender, e);
            }
        }

        private void tbPatientID_ButtonCustomClick(object sender, EventArgs e)
        {
            this.errorProvider1.Clear();

            if (object.Equals(((DevComponents.Editors.ComboItem)this.cbPatientType.SelectedItem), null))
            {
                this.errorProvider1.SetError(this.cbPatientType, "请选择病人类型");
                return;
            }

            if (tbPatientID.Text.Trim() == string.Empty)
            {
                this.errorProvider1.SetError(this.tbPatientID, "请输入申请条码");
                return;
            }
            try
            {
                DataSourceService dss = new DataSourceService();
                string str_type = ((DevComponents.Editors.ComboItem)this.cbPatientType.SelectedItem).Value.ToString();
                DataSourceModel dataSourceModel = dss.GetModelByID(str_type);
                //if (str_type == "门诊") dataSourceModel.SqlText = dataSourceModel.SqlText + " and sqh like '%" + tbPatientID.Text.Trim() + "%' order by sjrq desc";
                //if (str_type == "住院") dataSourceModel.SqlText = dataSourceModel.SqlText + " and sqh like '%" + tbPatientID.Text.Trim() + "%' order by sjrq desc";
                //if (str_type == "体检") dataSourceModel.SqlText = dataSourceModel.SqlText + " and djlsh ='" + tbPatientID.Text.Trim() + "'";

                if (str_type == "体检")
                    dataSourceModel.SqlText = dataSourceModel.SqlText + " and djlsh ='" + tbPatientID.Text.Trim() + "'";
                else
                    dataSourceModel.SqlText = dataSourceModel.SqlText + " and sqh like '%" + tbPatientID.Text.Trim() + "%'";

                DataTable dt_BrInfo = DataSourceModelExtend.QueryTable(dataSourceModel, dataSourceModel.SqlText);
                if (dt_BrInfo.Rows.Count > 0)//接口数据
                {
                    DataRow dataRow = null;
                    if (dt_BrInfo.Rows.Count > 1)
                    {
                        FrmCheckAppBrInfo frmCheckAppBrInfo = new FrmCheckAppBrInfo(dt_BrInfo);
                        if (frmCheckAppBrInfo.ShowDialog() == DialogResult.OK)
                        {
                            dataRow = frmCheckAppBrInfo.dataRow;
                        }
                    }
                    else
                    {
                        dataRow = dt_BrInfo.Rows[0];
                    }
                    tbPatientName.Tag = dataRow["brid"].ToString();
                    tbPatientName.Text = dataRow["xm"].ToString();
                    cbSext.SelectedValue = dataRow["xb"].ToString();
                    tbAge.Value = Convert.ToInt32(dataRow["nl"].ToString());
                    cbAgeUnit.SelectedValue = dataRow["nldw"].ToString();
                    tbBednum.Text = dataRow["ch"].ToString();
                    try
                    {
                        cbAppDepartment.SelectedValue = checkApp.GetKSID(dataRow["ks"].ToString());
                    }
                    catch { }
                    cbAppDoctor.Text = dataRow["sjys"].ToString();
                    dtAppTime.Value = Convert.ToDateTime(dataRow["sjrq"].ToString());
                    tbInterfaceCode.Text = dataRow["xmbh"].ToString();
                    cbCheckType.Text = dataRow["jclx"].ToString() == "" ? cbCheckType.Text : dataRow["jclx"].ToString();
                    cbItems.Text = dataRow["xmmc"].ToString();
                    //tbCheckPositionMothod.Text = dataRow["jcbw"].ToString();
                    tbDiagnose.Text = dataRow["lczd"].ToString();

                    tbCode.Text = PACS.Utility.SpellCode.SpellCodeHelper.GetFirstPYLetter(tbPatientName.Text.Trim());
                    dtBirthday.Value = DateTime.Now.AddYears(0 - this.tbAge.Value);

                }
                else
                {
                    tbPatientID.SelectAll();
                    MessageBoxEx.Show("申请条码输入有误，请检查", "申请", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch
            {
                MessageBoxEx.Show("接口程序配置有误，请联系系统管理人员", "申请", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void rbMz_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMz.Checked)
            {
                rbZy.Checked = false;
                rbTj.Checked = false;
                cbPatientType.Text = "门诊";
                this.ActiveControl = this.tbPatientID;
            }
        }

        private void rbZy_CheckedChanged(object sender, EventArgs e)
        {
            if (rbZy.Checked)
            {
                rbMz.Checked = false;
                rbTj.Checked = false;
                cbPatientType.Text = "住院";
                this.ActiveControl = this.tbPatientID;
            }
        }

        private void rbTj_CheckedChanged(object sender, EventArgs e)
        {
            if (rbTj.Checked)
            {
                rbMz.Checked = false;
                rbZy.Checked = false;
                cbPatientType.Text = "体检";
                this.ActiveControl = this.tbPatientID;
            }
        }
    }
}
